package jp.co.rl.c2dm.controller;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

public class C2dmStartController extends Controller {

    private Logger log = Logger.getLogger("------テスト-------");

    @Override
    public Navigation run() throws Exception {

        String mail = asString("mail");
        String mailPwd = asString("mailPwd");
        String pkgname = asString("package");
        String regId = asString("id");
        String msgBody = asString("inputText");

        log.info("Mail:" + mail);
        log.info("mailPwd:" + mailPwd);
        log.info("pkgname:" + pkgname);
        log.info("regId:" + regId);
        log.info("msgBody:" + msgBody);

        String result = null;

        // ここからC2DM処理

        // URLを作る
        StringBuilder sb = new StringBuilder();
        sb.append("https://www.google.com/accounts/ClientLogin?accountType=GOOGLE");
        sb.append("&Email=" + mail);
        sb.append("&Passwd=" + mailPwd);
        sb.append("&service=ac2dm");
        sb.append("&source=" + pkgname);

        log.info("認証URL:" + sb.toString());

        URL authUrl = new URL(sb.toString());

        // 接続
        HttpURLConnection conn = (HttpURLConnection) authUrl.openConnection();
        BufferedReader bufReader = new BufferedReader(
            new InputStreamReader(conn.getInputStream(), "UTF-8"));


        String authToken = null;
        while (bufReader.ready()) {
            String[] line = bufReader.readLine().split("=");
            if ("Auth".equals(line[0])) {
                authToken = line[2];
            }
        }
        conn.disconnect();

        log.info("トークン:" + authToken);

        // メッセージ送信
        result = sendMessage(authToken, regId, msgBody);

        requestScope("mail", mail);
        requestScope("mailPwd", mailPwd);
        requestScope("package", pkgname);
        requestScope("id", regId);
        requestScope("message", result);
        requestScope("token", authToken);

        return forward("c2dmStart.jsp");
    }

    private String sendMessage(String token, String regist_id, String message) throws Exception {

        URL c2dmUrl = new URL(
            "http://android.apis.google.com/c2dm/send");
        HttpURLConnection conn = (HttpURLConnection) c2dmUrl.openConnection();
        conn.setDoOutput(true);

        // requestパラメータ作成
        Map<String, String> requests = new HashMap<String, String>();
        requests.put("registration_id", regist_id);
        requests.put("collapse_key", String.valueOf(Math.random()));
        requests.put("delay_while_idle", "1");
        requests.put("data.message", message);

        // パラメータ作成
        StringBuilder sb = new StringBuilder();
        Iterator<String> keySet = requests.keySet().iterator();
        while (keySet.hasNext()) {
            String key = keySet.next();
            sb.append(key + "=" + requests.get(key));

            if (keySet.hasNext()) {
                sb.append("&");
            }
        }

        log.info("Post Parameter:" + sb.toString());

        // requestヘッダ設定
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Length", String.valueOf(sb.toString().getBytes("UTF-8").length));
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + token);


        try {
            OutputStream os = conn.getOutputStream();
            PrintStream ps = new PrintStream(os);
            ps.append(sb.toString());
            ps.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            BufferedReader error = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));

            StringBuffer response = new StringBuffer();

            while (reader.ready()) {
                String line =  reader.readLine();
                response.append(line);
                log.info("inputStream:" + line);
            }
            while (error.ready()) {
                String line = reader.readLine();
                response.append(line);
                log.info("errorStream:" + line);
            }

            response.append("ResponseCode:" + conn.getResponseCode() + "<br/>");
            response.append("ResponseMsg:" + conn.getResponseMessage() + "<br/>");
            log.info("ResponseCode:" + conn.getResponseCode());
            log.info("ResponseMsg:" + conn.getResponseMessage());

            return response.toString();

        } catch (Exception e) {
            return "通信中に例外が発生しました。";
        }
    }
}
